#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
网络连接测试脚本
用于测试Django服务器到OCR服务器的网络连接
"""

import requests
import time
import socket
from datetime import datetime

def test_network_connectivity():
    """测试网络连通性"""
    print("=" * 60)
    print("🌐 网络连接测试")
    print("=" * 60)
    
    ocr_server = "192.168.0.169"
    ocr_port = 5000
    
    # 1. Ping测试
    print(f"1. Ping测试: {ocr_server}")
    try:
        import subprocess
        result = subprocess.run(['ping', '-n', '1', ocr_server], 
                              capture_output=True, text=True, timeout=5)
        if result.returncode == 0:
            print("   ✅ Ping成功")
        else:
            print("   ❌ Ping失败")
    except Exception as e:
        print(f"   ❌ Ping测试异常: {e}")
    
    # 2. 端口连接测试
    print(f"2. 端口连接测试: {ocr_server}:{ocr_port}")
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(5)
        result = sock.connect_ex((ocr_server, ocr_port))
        sock.close()
        
        if result == 0:
            print("   ✅ 端口连接成功")
        else:
            print("   ❌ 端口连接失败")
    except Exception as e:
        print(f"   ❌ 端口测试异常: {e}")
    
    # 3. HTTP服务测试
    print(f"3. HTTP服务测试: http://{ocr_server}:{ocr_port}")
    try:
        response = requests.get(f'http://{ocr_server}:{ocr_port}/api/health', timeout=10)
        if response.status_code == 200:
            data = response.json()
            print("   ✅ HTTP服务正常")
            print(f"   服务状态: {data.get('status', 'unknown')}")
            print(f"   服务消息: {data.get('message', 'unknown')}")
        else:
            print(f"   ❌ HTTP服务异常: {response.status_code}")
    except requests.exceptions.Timeout:
        print("   ❌ HTTP服务超时")
    except requests.exceptions.ConnectionError:
        print("   ❌ HTTP服务连接失败")
    except Exception as e:
        print(f"   ❌ HTTP服务测试异常: {e}")

def test_ocr_api():
    """测试OCR API"""
    print("\n" + "=" * 60)
    print("🔍 OCR API测试")
    print("=" * 60)
    
    ocr_url = "http://192.168.0.169:5000/api/ocr/recognize"
    
    # 创建一个简单的测试图片（1x1像素的PNG）
    test_image_data = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\tpHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\nIDATx\x9cc```\x00\x00\x00\x04\x00\x01\xdd\x8d\xb4\x1c\x00\x00\x00\x00IEND\xaeB`\x82'
    
    try:
        files = {'image': ('test.png', test_image_data, 'image/png')}
        response = requests.post(ocr_url, files=files, timeout=30)
        
        if response.status_code == 200:
            data = response.json()
            if data.get('success'):
                print("   ✅ OCR API调用成功")
                print(f"   处理时间: {data.get('data', {}).get('processing_time', 'unknown')}秒")
                print(f"   识别结果: {data.get('data', {}).get('message', '无文字')}")
            else:
                print(f"   ❌ OCR API返回错误: {data.get('error', 'unknown')}")
        else:
            print(f"   ❌ OCR API响应异常: {response.status_code}")
    except requests.exceptions.Timeout:
        print("   ❌ OCR API调用超时")
    except requests.exceptions.ConnectionError:
        print("   ❌ OCR API连接失败")
    except Exception as e:
        print(f"   ❌ OCR API测试异常: {e}")

def test_django_integration():
    """测试Django集成"""
    print("\n" + "=" * 60)
    print("🐍 Django集成测试")
    print("=" * 60)
    
    try:
        # 测试Django OCR服务调用
        from ocr_service import check_ocr_service, recognize_image
        
        # 1. 检查OCR服务状态
        print("1. 检查OCR服务状态")
        is_available, status_info = check_ocr_service()
        if is_available:
            print("   ✅ OCR服务可用")
            print(f"   状态信息: {status_info}")
        else:
            print(f"   ❌ OCR服务不可用: {status_info}")
        
        # 2. 测试图片识别
        print("2. 测试图片识别")
        test_image_data = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\tpHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\nIDATx\x9cc```\x00\x00\x00\x04\x00\x01\xdd\x8d\xb4\x1c\x00\x00\x00\x00IEND\xaeB`\x82'
        
        # 模拟Django UploadedFile
        from django.core.files.uploadedfile import SimpleUploadedFile
        test_file = SimpleUploadedFile("test.png", test_image_data, content_type="image/png")
        
        result = recognize_image(test_file, "test.png")
        if result.get('success'):
            print("   ✅ Django OCR调用成功")
            print(f"   处理时间: {result.get('data', {}).get('processing_time', 'unknown')}秒")
        else:
            print(f"   ❌ Django OCR调用失败: {result.get('error', 'unknown')}")
            
    except ImportError as e:
        print(f"   ❌ Django模块导入失败: {e}")
        print("   请确保在Django环境中运行此测试")
    except Exception as e:
        print(f"   ❌ Django集成测试异常: {e}")

def main():
    """主函数"""
    print(f"🕐 测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"📍 Django服务器: 192.168.1.11:8000")
    print(f"📍 OCR服务器: 192.168.0.169:5000")
    
    # 执行所有测试
    test_network_connectivity()
    test_ocr_api()
    test_django_integration()
    
    print("\n" + "=" * 60)
    print("✅ 测试完成")
    print("=" * 60)
    
    print("\n📋 测试总结:")
    print("1. 如果网络连接测试失败，请检查:")
    print("   - OCR服务器是否正在运行")
    print("   - 防火墙是否开放5000端口")
    print("   - 网络连接是否正常")
    print("\n2. 如果OCR API测试失败，请检查:")
    print("   - OCR服务是否正确启动")
    print("   - PaddleOCR模型是否正确加载")
    print("\n3. 如果Django集成测试失败，请检查:")
    print("   - Django环境是否正确")
    print("   - ocr_service.py配置是否正确")

if __name__ == "__main__":
    main()
